#include <stdio.h>

// CBC加密

#define KEYSIZE 4

void enCode(int key[], int initialVector[], int plainText[], int plainSize, int cipherText[]) {
    if (plainSize % KEYSIZE != 0)
        return;
    // 先计算C0

    int size = plainSize / KEYSIZE;
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < KEYSIZE; j++) {
            if (i == 0) {
                cipherText[j] = (initialVector[j] + plainText[j] + key[j]) % 2;
                continue;
            }
            cipherText[j + i * KEYSIZE] = (cipherText[(i - 1) * KEYSIZE + j] + key[j] + plainText[j + i * KEYSIZE]) % 2;
        }
    }
}

int main() {
    int key[KEYSIZE] = { 1, 0, 0, 1 };
    int initialVector[KEYSIZE] = { 1, 0, 1, 1 };
    int plainText[] = { 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1 }; 
    int plainSize = sizeof(plainText) / sizeof(int);
    int cipherText[plainSize];
    enCode(key, initialVector, plainText, plainSize, cipherText);
    printf("加密结果为:");
    for (int i = 0; i < plainSize; i++)
        printf("%d ", cipherText[i]);
    printf("\n");
    return 0;
}